package me.yxy.mobanddd.components;

import lombok.Data;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * 基于{@link javax.persistence.EntityManager}的一个自定义分页执行器
 */
@Component
public class PageRepository {


    @PersistenceContext
    private EntityManager entityManager;

    public <T> MPage<T> query(String sql, Pageable pageable, Class<T> clz) {

        String countQuery = buildCountQuery(sql);
        Query query = entityManager.createNativeQuery(countQuery,CountBean.class);
        CountBean totalRows = (CountBean) query.getSingleResult();

        System.out.println(totalRows.getRows());

        return null;
    }


    /**
     * 去掉不需要的ORDER BY操作
     * @param sql
     * @return
     */
    private String buildCountQuery(String sql) {

        String SQL = sql.toUpperCase();
        int lastOrderByIndex = SQL.lastIndexOf(" ORDER ");

        //如果ORDER BY 出现在最后，那么可以删掉他们
        if(lastOrderByIndex >0 && endsWithOrderBy(SQL.substring(lastOrderByIndex))){
            sql =  sql.substring(0,lastOrderByIndex);
        }

        return "select count(*) as rows from (" + sql + ") a";
    }

    @Data
    public static class CountBean{
        private int rows;
    }

    private static final String[] SENSITIVE_KEYS = {"SELECT,FROM,WHERE,UNION,JOIN,ON"};

    private boolean endsWithOrderBy(String substring) {
        for (String key : SENSITIVE_KEYS) {
            if(substring.contains(" "+key+" ")){
                return false;
            }
        }
        return true;
    }
}
